﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq.Expressions;

namespace WindowsFormsApp1
{
    public partial class MainForm : Form
    {
        private TcpIpServer tcpIpServer;
        private TcpIpClient tcpIpClient;
       
        private TcpModbusClient tcpModbusClient;
        //private StreamWriter logWriter;
        //子窗体
        public modbusControl modbusControl;
        public tcpipControl tcpipControl;

        private Form2 form2;
        private Form3 form3;
        private Form4 form5;
        public MainForm()
        {
            InitializeComponent();
            //确保 MainForm_Load 方法已经绑定到了窗体的 Load 事件
            this.Load += new System.EventHandler(this.MainForm_Load);
            //tcpIpServer.DataReceived += OnDataReceived;  // 订阅 DataReceived 事件
        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void MainForm_Load(object sender, EventArgs e)
        {

            tcpipControl = new tcpipControl();
            // 设置子窗体的 TopLevel 属性为 false
            tcpipControl.CreateControl(); // 确保句柄已创建
            tcpipControl.OnSendData += TcpipControl_OnSendData; // 订阅事件
            tcpIpServer = new TcpIpServer(Log);
            tcpIpServer.DataReceived += OnDataReceived; // 确保订阅事件
            tcpIpClient = new TcpIpClient(Log);
            tcpIpClient.DataReceived += TcpClient_DataReceived;
            tcpModbusClient = new TcpModbusClient();
            Console.WriteLine("实例化 Form5");
            Form5 form5 = new Form5();
            Console.WriteLine("显示 Form5");
            form5.Show();
            modbusControl = new modbusControl();
            modbusControl.SetForm5(form5);
            cobProtocol.SelectedIndex = 0;
            //Console.WriteLine("MainForm_Load: tcpipControl initialized.");

            // 手动调用 cobProtocol_SelectedChanged 方法以初始化子窗体
            cobProtocol_SelectedChanged(cobProtocol, EventArgs.Empty);
        }

        private void TcpIpClient_DataReceived(string obj)
        {
            throw new NotImplementedException();
        }

        private void cobProtocol_SelectedChanged(object sender, EventArgs e)
        {
            string selectedProtocol = cobProtocol.SelectedItem.ToString();
            panel2.Controls.Clear();  // 清空原容器上的控件

            switch (selectedProtocol){
                case "TCP/IP Server":
                case "TCP/IP Client":
                    if (tcpipControl != null)
                    {
                        tcpipControl.Show();  // 将窗体显示
                        panel2.Controls.Add(tcpipControl);  // 将窗体加入容器 panel2
                    }
                    else
                    {
                        MessageBox.Show("tcpipcontrol is not initialized.");
                    }
                    break;

                case "ModbusTCP Client":
                    if (modbusControl != null)
                    {
                        modbusControl.SetMainForm(this); // Set reference to MainForm
                        modbusControl.Show();  // 将窗体显示
                        panel2.Controls.Add(modbusControl);  // 将窗体加入容器 panel2
                    }
                    else
                    {
                        MessageBox.Show("modbusControl is not initialized.");
                    }
                    break;
            }

        }

        
        //private void Log(string message)
        //{
        //    // 将日志信息显示在子窗体的日志显示框中
        //    //tcpipControl.Log(message);
        //    // 将日志信息显示在子窗体的日志显示框中
        //    if (tcpipControl.IsHandleCreated)
        //    {
        //        tcpipControl.Log(message);
        //    }
        //    else
        //    {
        //        // Handle the case where the handle is not created, e.g., by queuing the log message
        //        Console.WriteLine("Handle not created, log message: " + message);
        //    }
        //}
        private void Log(string message)
        {
            if (tcpipControl.InvokeRequired)
            {
                tcpipControl.Invoke(new Action<string>(Log), message);
            }
            else
            {
                tcpipControl.Log(message);
            }
        }
        private void TcpClient_DataReceived(string receivedData)
        {
            // 在 MainForm 中更新日志框
            Invoke(new Action(() =>
            {
                tcpipControl.Log($"Received from Client: {receivedData}");
            }));
            //string[] data = receivedData.Split(',');
            //if (data[0]== )
            // 将数据传递给 Form2 的 DataGridView
            Invoke(new Action(() =>
            {
                if (form2 == null || form2.IsDisposed)
                {
                    form2 = new Form2();
                    form2.Show();
                }

                string[] dataParts = receivedData.Split(','); // 假设数据是以逗号分隔的
                form2.UpdateDataGrid(dataParts);
            }));
        }

        private void OnDataReceived(string receivedData)
        {
            // 在 MainForm 中更新日志框
            Invoke(new Action(() =>
            {
                tcpipControl.Log($"Received: {receivedData}");
            }));

            

            // 将数据传递给 Form2 的 DataGridView
            Invoke(new Action(() =>
            {
                if (form2 == null || form2.IsDisposed)
                {
                    form2 = new Form2();
                    form2.Show();
                }

                string[] dataParts = receivedData.Split(','); // 假设数据是以逗号分隔的
                form2.UpdateDataGrid(dataParts);
            }));

            Invoke(new Action(() =>
            {
                if (form3 == null || form3.IsDisposed)
                {
                    form3 = new Form3();
                    form3.Show();
                }

                string[] dataParts = receivedData.Split(','); // 假设数据是以逗号分隔的
                form3.UpdateDataGrid(dataParts);
            }));
        }


        private bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        // Public methods to get IP address and port
        public string GetIpAddress()
        {
            return txtipAdress.Text.Trim();
        }

        public int GetPort()
        {
            return int.Parse(txtPort.Text.Trim());
        }
        private void btnOpen_Click(object sender, EventArgs e)
        {
            string ip = GetIpAddress();
            int port = GetPort();
            bool isValidIp = IsIP(ip);
            if (isValidIp) 
            {
                string selectProtocol = cobProtocol.Text.Trim();
                try
                {
                    bool isConnected = false;
                    switch (selectProtocol)
                    {
                        case "TCP/IP Server":
                            try
                            {
                                isConnected = tcpIpServer.Connect(ip, port);
                            }
                            catch (SocketException ex)
                            {
                                MessageBox.Show($"SocketException: {ex.Message}");
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                            break;
                        //case "TCP/IP Client":
                        //    isConnected = tcpIpClient.Connect(ip, port);
                        //    break;
                        case "ModbusTCP Client":
                            modbusControl.InitializeModbusMaster(); // Explicitly initialize here
                            isConnected = tcpModbusClient.Connect(ip, port);
                            break;
                        default:
                            MessageBox.Show("Invalid protocol selected.");
                            break;
                    }
                    if (isConnected)
                    {
                        lblMessageServer.Text = "连接成功！";
                        btnOpen.Enabled = false;
                    }
                    else
                {
                    lblMessageServer.Text = "连接失败！";
                }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("连接失败，" + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("无效的IP地址！");
            }
        }
        
        private void btnClose_Click(object sender, EventArgs e)
        {
            //if (btnOpen.Enabled == true)
            //{
            //    MessageBox.Show("还没有建立任何连接，不能关闭！");
            //    return;
            //}
            string selectProtocol = cobProtocol.Text.Trim();
            switch (selectProtocol)
            {
                case "TCP/IP Server":
                    try
                    {
                        tcpIpServer.Stop();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    break;
                case "TCP/IP Client":
                    tcpIpClient.Disconnect();
                    break;

                case "TCP Modbus Client":
                    tcpModbusClient.Disconnect();
                    break;
                //default:
                //    MessageBox.Show("Invalid protocol selected.");
                //    break;
            }
            MessageBox.Show("关闭成功！");
            btnOpen.Enabled = true;
            lblMessageServer.Text = "关闭成功！";
        }

        private void TcpipControl_OnSendData(string data)
        {
            string selectedProtocol = cobProtocol.SelectedItem.ToString();

            switch (selectedProtocol)
            {
                case "TCP/IP Server":
                    tcpIpServer.Send(data);
                    break;
                case "TCP/IP Client":
                    tcpIpClient.Send(data);
                    break;
                //case "TCP Modbus Client":
                //    tcpModbusClient.Send(data);
                //    break;
                default:
                    MessageBox.Show("Invalid protocol selected.");
                    break;
            }
        }

        /// <summary>
        /// 切换窗体
        /// </summary>
        private void OpenForm2()
        {
            if (form2 == null || form2.IsDisposed)
            {
                form2 = new Form2();
            }
            form2.Show();
            //this.Hide(); // 隐藏当前窗体
        }
        private void OpenForm3()
        {
            if (form3 == null || form3.IsDisposed)
            {
                form3 = new Form3();
            }
            form3.Show();
            //this.Hide(); // 隐藏当前窗体
        }

        //private void OpenForm4()
        //{
        //    if (form4 == null || form4.IsDisposed)
        //    {
        //        form4 = new Form4();
        //    }
        //    form4.Show();
        //    //this.Hide(); // 隐藏当前窗体
        //}
        private void btnChangeform_Click(object sender, EventArgs e)
        {
            OpenForm2();
        }

        private void buttonForm3_Click(object sender, EventArgs e)
        {
            OpenForm3();
        }

        private void buttonopenclient_Click(object sender, EventArgs e)
        {
            string ip = GetIpAddress();
            int port = GetPort();
            bool isValidIp = IsIP(ip);
            if (isValidIp)
            {
                string selectProtocol = cobProtocol.Text.Trim();
                try
                {
                    bool isConnected = false;
                    switch (selectProtocol)
                    {
                        //case "TCP/IP Server":
                        //    try
                        //    {
                        //        isConnected = tcpIpServer.Connect(ip, port);
                        //    }
                        //    catch (SocketException ex)
                        //    {
                        //        MessageBox.Show($"SocketException: {ex.Message}");
                        //    }
                        //    catch (Exception ex)
                        //    {
                        //        MessageBox.Show(ex.Message);
                        //    }
                        //    break;
                        case "TCP/IP Client":
                            isConnected = tcpIpClient.Connect(ip, port);
                            break;
                        case "ModbusTCP Client":
                            modbusControl.InitializeModbusMaster(); // Explicitly initialize here
                            isConnected = tcpModbusClient.Connect(ip, port);
                            break;
                        default:
                            MessageBox.Show("Invalid protocol selected.");
                            break;
                    }
                    if (isConnected)
                    {
                        lblMessageClient.Text = "连接成功！";
                        buttonopenclient.Enabled = false;
                    }
                    else
                    {
                        lblMessageClient.Text = "连接失败！";
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("连接失败，" + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("无效的IP地址！");
            }
        }

        private void buttonForm4_Click(object sender, EventArgs e)
        {
            //OpenForm4();
        }
    }
}
